﻿using ConnectorMsg;
using DotNetClient;
using Frameworks;
using GateMsg;
using System.Security.Cryptography;
using System.Text;
using UnityEngine;
using UnityEngine.UI;

public class HomeManager : MonoBehaviour
{
    [Header("Home")]
    public Button quite_btn;
    public Button login_btn;
    public Button register_btn;

    [Header("Login")]
    public GameObject login_panel;
    public InputField login_username;
    public InputField login_password;
    public Button login_confirm;
    public Button login_close;
    public Text login_tips;

    [Header("Register")]
    public GameObject register_panel;
    public InputField register_username;
    public InputField register_password;
    public Button register_confirm;
    public Button register_close;
    public Text register_tips;

    private string _host = "127.0.0.1";
    private int _port = 4001;

    private string _username = "fifthking";
    private string _password = "123456";

    private SocketClient _client;
    private bool _isInit = false;

    private void Awake()
    {

    }

    private void Start()
    {
        quite_btn.onClick.AddListener(() => { GameManager.Instance.QuitApp(); });
        login_btn.onClick.AddListener(openLoginPanel);
        register_btn.onClick.AddListener(openRegisterPanel);

        login_confirm.onClick.AddListener(requestLogin);
        login_close.onClick.AddListener(closeLoginPanel);

        register_confirm.onClick.AddListener(requestRegister);
        register_close.onClick.AddListener(closeRegisterPanel);

        EventProxy.AddEventListener(Routes.C2S_CONNECTOR_LOGIN, onResLogin);
        EventProxy.AddEventListener(Routes.C2S_CONNECTOR_REGISTER, onResRegister);

        closeLoginPanel();
        closeRegisterPanel();
        requestConnect();

        login_username.text = _username;
        login_password.text = _password;
    }

    private void Update()
    {
        
    }

    private void OnDestroy()
    {
        EventProxy.RemoveEventListener(Routes.C2S_CONNECTOR_LOGIN, onResLogin);
        EventProxy.RemoveEventListener(Routes.C2S_CONNECTOR_REGISTER, onResRegister);
    }

    // connect
    private void requestConnect()
    {
        if(!_isInit)
        {
            _client = new SocketClient();
            _client.NetWorkStateChangedEvent += (state) =>
            {
                Debug.Log("Gate NetWorkStateChangedEvent: " + state);
            };

            _client.InitClient(_host, _port, () =>
            {
                _client.Connect(() =>
                {
                    c2s_connect msg = new c2s_connect() { Username = _username };
                    _client.Request(Routes.C2S_GATE_CONNECT, msg, onResConnect);
                });
            });
        }
    }

    private void onResConnect(Message msg)
    {
        s2c_connect data = msg.decode<s2c_connect>();
        if (data.Code == (int)RETURN_CODE.SUCCESS)
        {
            _client?.Disconnect();
            _client = null;

            string host = data.Host;
            int port = data.Port;
            NetworkManager.Instance.InitClient(host, port, onResInit);
        }
    }

    private void onResInit()
    {
        _isInit = true;
        Debug.Log("网络初始化成功");
    }

    // login
    private void openLoginPanel()
    {
        login_panel.SetActive(true);
    }

    private void closeLoginPanel()
    {
        login_panel.SetActive(false);

        login_username.text = string.Empty;
        login_password.text = string.Empty;
        login_tips.text = string.Empty;
    }

    private void setLoginUI_Interactable(bool value)
    {
        login_username.interactable = value;
        login_password.interactable = value;
        login_confirm.interactable = value;
        login_close.interactable = value;
    }

    private void requestLogin()
    {
        if (!_isInit)
        {
            login_tips.text = "网络错误";
            return;
        }

        _username = login_username.text;
        _password = login_password.text;

        if (string.IsNullOrEmpty(_username) || string.IsNullOrEmpty(_password))
        {
            login_tips.text = "用户名和密码不能为空";
            return;
        }

        setLoginUI_Interactable(false);

        c2s_login user = new c2s_login() { Username = _username, Password = MD5Encrypt(_password) };
        NetworkManager.Instance.Request(Routes.C2S_CONNECTOR_LOGIN, user);
    }

    private void onResLogin(EventData eventData)
    {
        s2c_login data = (s2c_login)eventData.target;
        if (data.Code == (int)LOGIN_CODE.SUCCESS)
        {
            login_tips.text = "登录成功";

            MyselManager.Instance.Myself = data.User;
            MyselManager.Instance.Token = data.Token;

            closeLoginPanel();
            GameManager.SceneMgr.LoadSceneByLoading("Lobby");
        }
        else
        {
            switch ((LOGIN_CODE)data.Code)
            {
                case LOGIN_CODE.SUCCESS: login_tips.text = "登录成功"; break;
                case LOGIN_CODE.FAIL_NOT_EXIST: login_tips.text = "账号不存在"; break;
                case LOGIN_CODE.FAIL_WRONG: login_tips.text = "账号或密码错误"; break;
                case LOGIN_CODE.FAIL_DUPLICATE: login_tips.text = "重复登录"; break;
                default: break;
            }
        }

        setLoginUI_Interactable(true);
    }

    // register
    private void openRegisterPanel()
    {
        register_panel.SetActive(true);
    }

    private void closeRegisterPanel()
    {
        register_panel.SetActive(false);

        register_username.text = string.Empty;
        register_password.text = string.Empty;
        register_tips.text = string.Empty;
    }

    private void setRegisterUI_Interactable(bool value)
    {
        register_username.interactable = value;
        register_password.interactable = value;
        register_confirm.interactable = value;
        register_close.interactable = value;
    }

    private void requestRegister()
    {
        if (!_isInit)
        {
            register_tips.text = "网络错误";
            return;
        }

        _username = register_username.text;
        _password = register_password.text;

        if (string.IsNullOrEmpty(_username) || string.IsNullOrEmpty(_password))
        {
            register_tips.text = "用户名和密码不能为空";
            return;
        }

        setRegisterUI_Interactable(false);

        c2s_register user = new c2s_register() { Username = _username, Password = _password };
        NetworkManager.Instance.Request(Routes.C2S_CONNECTOR_REGISTER, user);
    }

    private void onResRegister(EventData eventData)
    {
        s2c_register data = (s2c_register)eventData.target;
        if (data.Code == (int)RETURN_CODE.SUCCESS)
        {
            register_tips.text = "注册成功";

            closeRegisterPanel();
        }
        else
        {
            switch ((RETURN_CODE)data.Code)
            {
                case RETURN_CODE.SUCCESS: register_tips.text = "注册成功"; break;
                case RETURN_CODE.ERROR: register_tips.text = "注册失败"; break;
                default: break;
            }
        }

        setRegisterUI_Interactable(true);
    }

    public string MD5Encrypt(string str)
    {
        MD5 md5 = MD5.Create();
        byte[] bytes = Encoding.UTF8.GetBytes(str);
        byte[] target = md5.ComputeHash(bytes);
        StringBuilder hashString = new StringBuilder();
        for (int i = 0; i < target.Length; i++)
        {
            hashString.AppendFormat("{0:x2}", target[i]);
        }
        return hashString.ToString();
    }
}
